package com.gistone.commis.api.restController;

import com.gistone.commis.dto.*;
import com.gistone.commis.entity.*;
import com.gistone.commis.mapper.CommunityMapper;
import com.gistone.commis.mapper.DepartMapper;
import com.gistone.commis.mapper.FixedItemMapper;
import com.gistone.commis.util.DataTablePageUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by wangfan on 2017/5/5.
 */
@RestController("apiFixedItemController")
@RequestMapping("api/fixedItem")
public class FixedItemController {

    private static final Logger logger = LoggerFactory.getLogger(FixedItemController.class);


    @Autowired
    private FixedItemMapper fixedItemMapper;

    @Autowired
    private CommunityMapper communityMapper;

    @Autowired
    private DepartMapper departMapper;


    /**
     * 根据id获取工资固定项信息
     * @param id
     * @return
     */

    @RequestMapping(method = RequestMethod.GET, value = "/{id}")
    public FixedItem fixedItem(@PathVariable int id) {
        FixedItem fixedItem =fixedItemMapper.selectByPrimaryKey(id);
        return fixedItem;
    }






    /**
     * 新建工资固定项信息
     *
     * @param request
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    public Object create(HttpServletRequest request, HttpServletResponse response,Integer id) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");

        FixedItem fixedItem = new FixedItem();
        EditorResult<FixedItem> fixedItemEditorResult = new EditorResult<>();

        List<FieldError> fieldErrorList = new ArrayList<>();

        getFixedItem(request, "data[0][", fixedItem,fieldErrorList);
        fixedItem.setRegisterTime(new Date());



//        System.out.println(fixedItemId);

        if(fieldErrorList.size()>0){
            logger.error("字段格式错误");
            fixedItemEditorResult.setFieldErrors(fieldErrorList);
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return fixedItemEditorResult;
        }
        if (fixedItemMapper.insertSelective(fixedItem) > 0) {
            logger.info("fixedItemId--"+fixedItem.getId());
            List<FixedItem> data = new ArrayList<>();
            data.add(fixedItem);
            fixedItemEditorResult.setData(data);
        } else {
            response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
        }


        return fixedItemEditorResult;
//
    }

    /**
     * 批量修改工资固定项信息， id以,号分割
     *
     * @param fixedItemIdStr
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.PUT, value = "/edit")
    public Object edit(@RequestParam("id") String fixedItemIdStr, HttpServletRequest request, HttpServletResponse response) {

        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        String[] arr = fixedItemIdStr.split(",");
        EditorResult<FixedItem> fixedItemEditorResult = new EditorResult<>();
        List<FixedItem> data =new ArrayList<>();

        for (int i = 0; i < arr.length; i++) {
            int fixedItemId = Integer.valueOf(arr[i]);
            FixedItem fixedItem = new FixedItem();
            fixedItem.setId(fixedItemId);
            List<FieldError> fieldErrorList = new ArrayList<>();
            getFixedItem(request, "data[" + fixedItemId + "][", fixedItem,fieldErrorList);
//            fixedItem = getDotFixedItem(request, "data." + fixedItemId + ".", fixedItem);
            if(fieldErrorList.size()>0){
                logger.error("字段错误");
                fixedItemEditorResult.setFieldErrors(fieldErrorList);
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                return fixedItemEditorResult;
            }
            if (fixedItemMapper.updateByPrimaryKeySelective(fixedItem) > 0) {
                FixedItem h = fixedItemMapper.selectByPrimaryKey(fixedItemId);
                data.add(h);

              







            }else{
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }


        }
        fixedItemEditorResult.setData(data);
        return fixedItemEditorResult;


    }


    /**
     * 用房删除
     * 通过工资固定项ID批量删除工资固定项信息， id以,号分割
     *
     * @param fixedItemIdStr
     * @param response
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = "/remove")
    public Object remove(@RequestParam("id") String fixedItemIdStr, HttpServletResponse response) {
        String[] arr = fixedItemIdStr.split(",");
        EditorResult<FixedItem> fixedItemEditorResult = new EditorResult<>();
        for (int i = 0; i < arr.length; i++) {
            int fixedItemId = Integer.valueOf(arr[i]);
            FixedItem fixedItem =new FixedItem();
            fixedItem.setId(fixedItemId);
//            fixedItem.setIsDelete(1);
            if (fixedItemMapper.updateByPrimaryKeySelective(fixedItem) > 0) {
                System.out.println("删除" + fixedItemId + "成功！");


            } else {
                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            }
        }
        return fixedItemEditorResult;


    }

    /**
     * dataTables 表单数据返回
     *
     * @param request
     * @return
     */

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = "/pageDatatables")
    public DataTablePageUtil<FixedItem> pageDatatables(HttpServletRequest request, FixedItem fixedItem) {
/*        HttpSession httpSession = request.getSession();
        User user = (User) httpSession.getAttribute("userInfo");
        logger.info("用户信息：" + user.toString());
        int community_id = user.getCommunity().getCommunityId();
        fixedItem.setCommunityId(community_id);*/

        List<Community> communities =communityMapper.findCommunitys();
        Options os =new Options();
        List<Option> optionList =new ArrayList<>();
        for (Community community : communities) {

            Option option =new Option();
            option.setLabel(community.getCommunityName());
            option.setValue(community.getCommunityId());
            optionList.add(option);


        }
        os.setCommunityId(optionList);
        List<Depart> departs =departMapper.findDeparts();
        optionList =new ArrayList<>();
        for (Depart depart : departs) {

            Option option =new Option();
            option.setLabel(depart.getDepartName());
            option.setValue(depart.getDepartId());
            optionList.add(option);


        }

        os.setDepartId(optionList);



        DataTablePageUtil<FixedItem> dataTable = new DataTablePageUtil<>(request);
//        fixedItem.setIsDelete(0);
        PageHelper.startPage(dataTable.getPage_num(), dataTable.getPage_size());
        List<FixedItem> list = fixedItemMapper.selectSelective(fixedItem);
        PageInfo<FixedItem> pageInfo =new PageInfo<>(list);

        System.out.println(list.size());
        dataTable.setDraw(dataTable.getDraw());
        dataTable.setData(pageInfo.getList());
        dataTable.setOptions(os);
        dataTable.setRecordsTotal((int)pageInfo.getTotal());
        dataTable.setRecordsFiltered(dataTable.getRecordsTotal());
        //返回数据到页面


        return dataTable;

    }




    private void getFixedItem(HttpServletRequest request, String prefix, FixedItem fixedItem,  List<FieldError> fieldErrorList ) {

        try {
            fixedItem.setDsznSub(Double.valueOf(request.getParameter(prefix + "dsznSub]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("dsznSub","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setWorkSub(Double.valueOf(request.getParameter(prefix + "workSub]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("workSub","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setExistSub(Double.valueOf(request.getParameter(prefix + "existSub]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("existSub","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setMonthBonus(Double.valueOf(request.getParameter(prefix + "monthBonus]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("monthBonus","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setPerBonus(Double.valueOf(request.getParameter(prefix + "perBonus]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("perBonus","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
       /* try {
            fixedItem.setPensionRatio(Double.valueOf(request.getParameter(prefix + "pensionRatio]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("pensionRatio","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setMedicareRatio(Double.valueOf(request.getParameter(prefix + "medicareRatio]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("medicareRatio","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setUnemploymentRatio(Double.valueOf(request.getParameter(prefix + "unemploymentRatio]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("unemploymentRatio","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setProvidentFund(Double.valueOf(request.getParameter(prefix + "providentFund]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("providentFund","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setIncomeTaxRatio(Double.valueOf(request.getParameter(prefix + "incomeTaxRatio]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("incomeTaxRatio","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setBkgjj(Double.valueOf(request.getParameter(prefix + "bkgjj]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("bkgjj","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setBksx(Double.valueOf(request.getParameter(prefix + "bksx]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("bksx","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }
        try {
            fixedItem.setSjRatio(Double.valueOf(request.getParameter(prefix + "sjRatio]")));
        } catch (NumberFormatException e) {
            logger.error("格式不正确，必须为double型");
            FieldError fieldError =new FieldError("sjRation","格式不正确，必须为double型");
            fieldErrorList.add(fieldError);
        }*/




    }

}
